// module "my-module.js"
//需要traverson和traverson-hal
import traverson from "traverson";
import JsonHalAdapter from "traverson-hal";
// register the traverson-hal plug-in for media type 'application/hal+json'
traverson.registerMediaType(JsonHalAdapter.mediaType, JsonHalAdapter);
let baseURL = "http://192.168.0.114:8080/";
// 注册traverson-Hal插件for media type 'application/hal+json'
function save(path, payload) {
  // use Traverson to follow links, as usual
  let url = baseURL + path;
  traverson
    .from(url)
    .jsonHal()
    .post(payload, (error, response) => {
      if (error) {
        console.error("网络发生错误,请重试");
      } else {
        if (response.statusCode == "201")
          console.log("请求成功并且服务器创建了新的资源: ");
        console.log("新的资源内容: " + response.body);
      }
    });
}
function remove(headers = undefined, path, payload, callback) {
  // use Traverson to follow links, as usual
  let url = baseURL + path;
  if (typeof headers == "undefined") {
    traverson
      .from(url)
      .jsonHal()
      .delete(payload, callback);
  } else {
    traverson
      .from(url)
      .jsonHal()
      .withRequestOptions({ headers: headers })
      .delete(payload, callback);
  }
}

function alter(headers = undefined, path, payload, callback) {
  // use Traverson to follow links, as usual
  let url = baseURL + path;
  if (typeof headers == "undefined") {
    traverson
      .from(url)
      .jsonHal()
      .patch(payload, callback);
  } else {
    traverson
      .from(url)
      .jsonHal()
      .withRequestOptions({ headers: headers })
      .patch(payload, callback);
  }
}
function get(path, links) {
  // use Traverson to follow links, as usual
  let url = baseURL + path;
  traverson
    .from(url)
    .jsonHal()
    .follow(links)
    .get((error, response, traversal) => {
      if (error) {
        console.error("网络发生错误,请重试:" + error);
      } else {
        if (response.statusCode == "201")
          console.log("请求成功并且服务器创建了新的资源: ");
        console.log("新的资源内容: " + response.body);
        console.log(traversal);
      }
    });
}
export { alter, get, remove, save };
